import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Header from '../../components/Header'
import CurrentCity from '../../components/CurrentCity'
import CityList from '../../components/CityList'
import * as userInfoActionsFromOtherFile from '../../actions/userinfo'

import LocalStore from '../../util/localStore'
import { CITYNAME } from '../../config/localStoreKey'

import { hashRouter } from 'react-router-dom'


class City extends React.Component {
  constructor(props, context){
    super(props, context);
  }
  render(){
    return (
      <div>
        <Header title="选择城市"/>
        <CurrentCity cityName={this.props.userinfo.cityName}/>
        <CityList changeFn={this.changeCity.bind(this)}/>
      </div>
    );
  }
  componentDidMount(){
    // console.log(this.props.userinfo);
    // console.log(this.props.userinfoActions);

    // console.log(localStore);
    // console.log(CITYNAME);
  }

  changeCity(newCity){
    if(newCity == null){
      return
    }
    // 将新选择的城市设置为当前城市
    // 1. 修改 redux
    const userinfo = this.props.userinfo;
    userinfo.cityName = newCity;
    this.props.userInfoActions.update(userinfo);

    // 2. 修改 localStoreage
    LocalStore.setItem(CITYNAME, newCity);

    // 3. 跳转到首页
    this.props.history.push("/");
  }
}

// ---------redux react 绑定-----------
function mapStateToProps(state) {
  return {
    userinfo: state.userinfo
  }
}

function mapDispatchToProps(dispatch) {
  return {
    userInfoActions: bindActionCreators(userInfoActionsFromOtherFile, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps)
(City);


